import * as React from 'react';
import { Layout, Menu, Icon } from 'antd';
import { Link } from 'react-router-dom';
import { MenuMode } from 'antd/lib/menu';
import menuConfig from '../../config/menu';
import logo from '../../../assets/images/logo-with-name.png';
import './index.less'

import { loginCtx } from '../QQLogin/LoginProvider';

const SubMenu = Menu.SubMenu
const { Sider } = Layout;

const {
    useState,
    useEffect
} = React;

function SideBarMenu(nodes = [], role) {
    return nodes.map((item, i) => {
        const menu = SideBarMenu(item.child, role);

        const {
            showInMenu = true,
            authority = []
        } = item;

        // 鉴权
        if (authority.length !== 0 && !authority.includes(role)) {
            return null;
        }

        if (menu.length > 0) {
            return (
                <SubMenu
                    key={item.key}
                    title={<span><Icon type={item.icon} /><span className="nav-text">{item.name}</span></span>}
                >
                    {menu}
                </SubMenu>
            );
        } else {
            return (
                showInMenu ? (
                    <Menu.Item key={item.key}>
                        <Link to={item.path}>
                            {<Icon type={item.icon}/>}
                            <span>{item.name}</span>
                        </Link> 
                    </Menu.Item>
                ) : null
            );
        }
    });
}

export default function Sidebar(props) {
    const {
        items = menuConfig,
        openKeys = menuConfig.map((item) => item.key),
        activeKey = '',
        collapsed,
        mode
    } = props;

    return (
        <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            style={{
                overflow: 'auto', height: '100vh', position: 'fixed', left: 0,
            }}
        >
            <img className="ant-layout-logo" src={logo}></img>
            <loginCtx.Consumer>
                { 
                    value => value.userInfo ?  (
                        <Menu
                            mode={mode as MenuMode} theme="dark"
                            selectedKeys={[activeKey]}
                            defaultOpenKeys={openKeys}
                        >
                            {
                                SideBarMenu(items, value.userInfo.role)
                            }
                        </Menu>
                    ): null
                }
            </loginCtx.Consumer>               
        </Sider>
    )
}